from datetime import datetime
from sys import audit

from src.api.ArticleRouter.resource import ptool
from src.init.init_db import db
from src.model.ALikeModel import ALikeModel
from src.model.AritcleModel import ArticleModel
from src.model.UserModel import UserModel
from src.model.TypeModel import TypeModel
from src.utils.comment_tool import CommentTool
from src.utils.picture_tool import PictureTool
from src.utils.type_tool import TypeTool

ctool = CommentTool()
ttool = TypeTool()
ptool = PictureTool()


class ArticleTool:

    def init(self, uid:int):
        article = ArticleModel.query.filter_by(uid=uid, audit=False).first()
        if article is not None:
            return {"aid":article.aid}
        self.uid = uid
        article = ArticleModel(uid=uid, title='wait_commit', audit=False)
        db.session.add(article)
        db.session.commit()
        return {"aid":article.aid}


    def update_article(self, aid:int, title:str="标题", content:str="内容", tid:int=0):
        article = ArticleModel.query.filter_by(aid=aid).first()
        if article is None:
            return {"success":False, "err":"文章不存在！"}
        if TypeModel.query.filter_by(tid=tid).first() is None:
            return {"success":False, "err":"标签不存在！"}
        article.title = title
        article.content = content
        article.tid = tid
        article.audit = True
        article.createtime = datetime.now()
        db.session.commit()
        return {"success":True}


    def delete_article(self, aid:int, uid:int):
        user = UserModel.query.filter_by(uid=uid).first()
        article = ArticleModel.query.filter_by(aid=aid).first()
        if user is None:
            return {"success":False, "err":"用户不存在！"}
        # 当前用户是管理员用户
        if user.role != 0:
            if article is None:
                return {"success":False, "err":"文章不存在！"}
            ptool.delete_picture(article.aid)
            db.session.delete(article)
            db.session.commit()
            return {"success":True}
        # 当前用户为普通用户
        article = ArticleModel.query.filter_by(aid=aid, uid=uid).first()
        if article is None:
            return {"success":False, "err":"您没有权限！"}
        ptool.delete_picture(article.aid)
        db.session.delete(article)
        db.session.commit()
        return {"success":True}



    def filter_list(self, tids: list, articles: ArticleModel) -> dict:
        """
        :param tids: 需要过滤掉的tid
        :param articles: 文章信息
        """
        count = 0
        datalist = []

        for article in articles:
            if article.tid in tids or article.audit is False:
                continue
            count += 1

            tmp_data = {"aid": article.aid, "articleTitle": article.title, "views": article.view}
            datalist.append(tmp_data)

        data = {'count': count, 'datalist': datalist}
        return data

    def get_list(self, tids: list, articles: ArticleModel) -> dict:
        """
        :param tids: 需要查找的tid集合
        :param articles: 文章信息
        """
        count = 0
        datalist = []
        for article in articles:
            if article.tid not in tids or article.audit is False:
                continue
            count += 1

            tid = TypeModel.query.filter_by(name="已经被领取的任务").first().tid
            if article.tid == tid:
                tmp_data = {"aid": article.aid, "articleTitle": article.title, "views": article.view, "state": "ack"}
            else:
                tmp_data = {"aid": article.aid, "articleTitle": article.title, "views": article.view, "state": "wait"}
            datalist.append(tmp_data)
        data = {'count': count, 'datalist': datalist}
        return data

    def get_by_type(self, articles: ArticleModel, types: str) -> dict:
        """
        :param articles: 文章
        :param types: 查找的文章类型
        根据查找的文章类型返回对应的文章数据
        """
        data = None
        if types == 'article':
            # 获取tid对应的type为公告和任务的文章
            # 暂未完成 tids为公告、任务
            tids = ttool.list_task_tags() + ttool.list_announce_tags()
            data = self.filter_list(tids, articles)
        elif types == 'notice':
            # 获取tid对应的type为公告的文章
            # 暂未完成 tids为公告
            tids = ttool.list_announce_tags()
            data = self.get_list(tids, articles)

        elif types == 'task':
            # 获取tid对应的type为任务的文章
            # 暂未完成 tids为任务
            tids = ttool.list_task_tags()
            data = self.get_list(tids, articles)

        return data

    def get_article(self, article: ArticleModel, uid: int) -> dict:
        """
        :param article: 文章
        :param uid: 用户id
        查找对应文章的内容，和评论信息
        """
        data = {'aid': article.aid, 'articleTitle': article.title, 'views': article.view + 1,
                'createTime': article.createtime, 'content': article.content}

        # time 格式转换
        data['createTime'] = data['createTime'].strftime("%Y年%m月%d日 %H:%M:%S")
        # name 查找
        name = UserModel.query.filter_by(uid=article.uid).first().name
        data['name'] = name
        # like 查找
        like = False
        if uid != 0:
            like = True if ALikeModel.query.filter_by(aid=article.aid, uid=uid).first() is not None else False
        data['like'] = like
        # alike 查找
        alikes = ALikeModel.query.filter_by(aid=article.aid).count()
        data['alikes'] = alikes
        # comment 查找
        commentList = ctool.get_comment(article.aid, uid)
        data['commentList'] = commentList

        return data
